package org.jeecg.modules.pipe.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.modules.device.entity.DevDeviceInfo;
import org.jeecg.modules.device.service.IDevDeviceInfoService;
import org.jeecg.modules.device.service.IDevDeviceRecordService;
import org.jeecg.modules.drive.service.DriveCommonInterfaceService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.pipe.entity.CraftDevice;
import org.jeecg.modules.pipe.entity.CraftInfo;
import org.jeecg.modules.pipe.vo.CraftInfoPage;
import org.jeecg.modules.pipe.service.ICraftInfoService;
import org.jeecg.modules.pipe.service.ICraftDeviceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 工艺图
 * @Author: jeecg-boot
 * @Date:   2024-06-04
 * @Version: V1.0
 */
@Api(tags="工艺图")
@RestController
@RequestMapping("/pipe/craftInfo")
@Slf4j
public class CraftInfoController {
	@Autowired
	private ICraftInfoService craftInfoService;
	@Autowired
	private ICraftDeviceService craftDeviceService;
	@Autowired
	private IDevDeviceInfoService devDeviceInfoService;
	@Autowired
	private IDevDeviceRecordService deviceRecordService;
	@Autowired
	private DriveCommonInterfaceService commonInterfaceService;

	/**
	 * 分页列表查询
	 *
	 * @param craftInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "工艺图-分页列表查询")
	@ApiOperation(value="工艺图-分页列表查询", notes="工艺图-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CraftInfo>> queryPageList(CraftInfo craftInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CraftInfo> queryWrapper = QueryGenerator.initQueryWrapper(craftInfo, req.getParameterMap());
		Page<CraftInfo> page = new Page<CraftInfo>(pageNo, pageSize);
		IPage<CraftInfo> pageList = craftInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param craftInfoPage
	 * @return
	 */
	@AutoLog(value = "工艺图-添加")
	@ApiOperation(value="工艺图-添加", notes="工艺图-添加")
	// @RequiresPermissions("pipe:iot_dev_craft_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CraftInfoPage craftInfoPage) {
		CraftInfo craftInfo = new CraftInfo();
		BeanUtils.copyProperties(craftInfoPage, craftInfo);
		craftInfoService.saveMain(craftInfo, craftInfoPage.getCraftDeviceList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param craftInfoPage
	 * @return
	 */
	@AutoLog(value = "工艺图-编辑")
	@ApiOperation(value="工艺图-编辑", notes="工艺图-编辑")
	// @RequiresPermissions("pipe:iot_dev_craft_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CraftInfoPage craftInfoPage) {
		CraftInfo craftInfo = new CraftInfo();
		BeanUtils.copyProperties(craftInfoPage, craftInfo);
		CraftInfo craftInfoEntity = craftInfoService.getById(craftInfo.getId());
		if(craftInfoEntity==null) {
			return Result.error("未找到对应数据");
		}
		craftInfoService.updateMain(craftInfo, craftInfoPage.getCraftDeviceList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "工艺图-通过id删除")
	@ApiOperation(value="工艺图-通过id删除", notes="工艺图-通过id删除")
	// @RequiresPermissions("pipe:iot_dev_craft_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		craftInfoService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "工艺图-批量删除")
	@ApiOperation(value="工艺图-批量删除", notes="工艺图-批量删除")
	// @RequiresPermissions("pipe:iot_dev_craft_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.craftInfoService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "工艺图-通过id查询")
	@ApiOperation(value="工艺图-通过id查询", notes="工艺图-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CraftInfo> queryById(@RequestParam(name="id",required=true) String id) {
		CraftInfo craftInfo = craftInfoService.getById(id);
		if(craftInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(craftInfo);

	}

	 /**
	  * 通过水厂获取工艺图
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "工艺图-通过id查询")
	 @ApiOperation(value="工艺图-通过水厂获取工艺图", notes="工艺图-通过水厂获取工艺图")
	 @GetMapping(value = "/queryByPlantId")
	 public Result<CraftInfo> queryByPlantId(@RequestParam(name="id",required=true) String id) {
		 CraftInfo craftInfo = craftInfoService.getOne(Wrappers.<CraftInfo>lambdaQuery().eq(CraftInfo::getPlantId, id));
		 if(craftInfo==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(craftInfo);
	 }


	 /**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "工艺图设备通过主表ID查询")
	@ApiOperation(value="工艺图设备主表ID查询", notes="工艺图设备-通主表ID查询")
	@GetMapping(value = "/queryCraftDeviceByMainId")
	public Result<List<CraftDevice>> queryCraftDeviceListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CraftDevice> craftDeviceList = craftDeviceService.selectByMainId(id);
		for (CraftDevice craftDevice : craftDeviceList) {
			craftDevice.setDeviceName(devDeviceInfoService.getById(craftDevice.getDeviceId()).getDeviceName());
		}
		return Result.OK(craftDeviceList);
	}

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "工艺图设备通过主表ID查询")
	 @ApiOperation(value="工艺图设备主表ID查询", notes="工艺图设备-通主表ID查询")
	 @GetMapping(value = "/queryCraftDeviceByPlant")
	 public Result<List<CraftDevice>> queryCraftDeviceListByPlant(@RequestParam(name="id",required=true) String id) {
		 CraftInfo craftInfo = craftInfoService.getOne(Wrappers.<CraftInfo>lambdaQuery().eq(CraftInfo::getPlantId, id));
		 if(null == craftInfo){
			 return Result.error("无工艺图数据");
		 }
		 List<CraftDevice> craftDeviceList = craftDeviceService.selectByMainId(craftInfo.getId());
		 for (CraftDevice craftDevice : craftDeviceList) {
			 craftDevice.setDeviceName(devDeviceInfoService.getById(craftDevice.getDeviceId()).getDeviceName());
		 }
		 return Result.OK(craftDeviceList);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param craftInfo
    */
    // @RequiresPermissions("pipe:iot_dev_craft_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CraftInfo craftInfo) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<CraftInfo> queryWrapper = QueryGenerator.initQueryWrapper(craftInfo, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
          List<String> selectionList = Arrays.asList(selections.split(","));
          queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<CraftInfo> craftInfoList = craftInfoService.list(queryWrapper);

      // Step.3 组装pageList
      List<CraftInfoPage> pageList = new ArrayList<CraftInfoPage>();
      for (CraftInfo main : craftInfoList) {
          CraftInfoPage vo = new CraftInfoPage();
          BeanUtils.copyProperties(main, vo);
          List<CraftDevice> craftDeviceList = craftDeviceService.selectByMainId(main.getId());
          vo.setCraftDeviceList(craftDeviceList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "工艺图列表");
      mv.addObject(NormalExcelConstants.CLASS, CraftInfoPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("工艺图数据", "导出人:"+sysUser.getRealname(), "工艺图"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    // @RequiresPermissions("pipe:iot_dev_craft_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<CraftInfoPage> list = ExcelImportUtil.importExcel(file.getInputStream(), CraftInfoPage.class, params);
              for (CraftInfoPage page : list) {
                  CraftInfo po = new CraftInfo();
                  BeanUtils.copyProperties(page, po);
                  craftInfoService.saveMain(po, page.getCraftDeviceList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  * 通过工艺图ID查询设备实时数据
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "工艺图-通过id查询")
	 @ApiOperation(value="通过工艺图ID查询设备实时数据", notes="通过工艺图ID查询设备实时数据")
	 @GetMapping(value = "/getDeviceRealDataByCraft")
	 public Result<JSONArray> getDeviceRealDataByCraft(@RequestParam(name="id",required=true) String id) {

		 JSONArray rsLs = new JSONArray();
		 List<CraftDevice> craftDeviceList = craftDeviceService.selectByMainId(id);
		 if(null != craftDeviceList && craftDeviceList.size()>0){
			 for (CraftDevice craftDevice : craftDeviceList) {
				 String deviceId = craftDevice.getDeviceId();
				 /**
				  * mapJson.put("deviceType", map.get("deviceType").toString());
				  * mapJson.put("deviceValue", map.get("deviceValue").toString());
				  * mapJson.put("deviceUnit", map.get("deviceUnit").toString());
				  * mapJson.put("uniqueId", uniqueId);
				  */
				 JSONObject deviceData = deviceRecordService.getDeviceRecordByCode(deviceId);
				 rsLs.add(deviceData);
			 }
		 }
		 return Result.OK(rsLs);
	 }


	 /**
	  * 通过水厂ID查询工艺图设备的实时数据
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "工艺图-通过id查询")
	 @ApiOperation(value="通过水厂ID查询工艺图设备的实时数据", notes="通过水厂ID查询工艺图设备的实时数据")
	 @GetMapping(value = "/getDeviceRealDataByPlant")
	 public Result<JSONArray> getDeviceRealDataByPlant(@RequestParam(name="id",required=true) String id) {
		 JSONArray rsLs = new JSONArray();

		 CraftInfo craftInfo = craftInfoService.getOne(Wrappers.<CraftInfo>lambdaQuery().eq(CraftInfo::getPlantId, id));
		 if(null == craftInfo){
			 return Result.error("无工艺图数据");
		 }

		 List<CraftDevice> craftDeviceList = craftDeviceService.selectByMainId(craftInfo.getId());
		 if(null != craftDeviceList && craftDeviceList.size()>0){
			 for (CraftDevice craftDevice : craftDeviceList) {
				 String deviceId = craftDevice.getDeviceId();
				 /**
				  * mapJson.put("deviceType", map.get("deviceType").toString());
				  * mapJson.put("deviceValue", map.get("deviceValue").toString());
				  * mapJson.put("deviceUnit", map.get("deviceUnit").toString());
				  * mapJson.put("uniqueId", uniqueId);
				  */
				 JSONObject deviceData = deviceRecordService.getDeviceRecordByCode(deviceId);
				 rsLs.add(deviceData);
			 }
		 }
		 return Result.OK(rsLs);
	 }

	 /**
	  * 通过设备ID查询设备实时数据
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "工艺图-通过id查询")
	 @ApiOperation(value="通过设备ID查询设备实时数据", notes="通过设备ID查询设备实时数据")
	 @GetMapping(value = "/getDeviceRealDataByUniqueId")
	 public Result<JSONArray> getDeviceRealDataByUniqueId(@RequestParam(name="id",required=true) String id) {

		 JSONArray rsLs = new JSONArray();

		 DevDeviceInfo deviceInfo = devDeviceInfoService.getById(id);
		 /**
		  * mapJson.put("deviceType", map.get("deviceType").toString());
		  * mapJson.put("deviceValue", map.get("deviceValue").toString());
		  * mapJson.put("deviceUnit", map.get("deviceUnit").toString());
		  * mapJson.put("uniqueId", uniqueId);
		  */
		 if(null == deviceInfo){
			 return Result.error("无设备无数据");
		 }
		 JSONObject detailObj = JSONObject.parseObject(JSON.toJSONString(deviceInfo));
		 JSONObject deviceData = deviceRecordService.getDeviceRecordByCode(id);
		 if(null == deviceData ){
			 deviceData = new JSONObject();
		 }
		 deviceData.put("detail",detailObj);

		 // 获取监控设备播放地址，?? 需要替换成设备序列号
		 if("5".equals(deviceInfo.getDeviceType())){
		 	String playAddress = commonInterfaceService.getMonitorDevicePlayByInterface(deviceInfo);
			 playAddress = playAddress.replace("??",deviceInfo.getDeviceId());
			 deviceData.put("playAddress",playAddress);
		 }
		 rsLs.add(deviceData);

		 return Result.OK(rsLs);
	 }
}
